﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Data;
using System.ComponentModel;
using System.Data.OracleClient;



public class EntityOprHelper : Attribute
    {
       
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public T GetEntity<T>(string key) where T : new()
        {
            T t = new T();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

            // return t;
            StringBuilder strSql = new StringBuilder();
            DBType dbType = OConfig.SysDBType;
           IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);


            strSql.Append("select  ");
            strSql.Append(" * ");
            strSql.Append(" from ");
            strSql.Append(classAttribute.TableName);
            strSql.Append(" where ");


            strSql.Append(classAttribute.KeyName + "='" + key + "' ");

            DataSet ds = DB.ExecuteDataSet(strSql.ToString(), CommandType.Text, null);
            if (ds.Tables.Count >= 1)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {
                    foreach (PropertyInfo p in properties)
                    {
                        if (ds.Tables[0].Columns.Contains(p.Name) && ds.Tables[0].Rows[0][p.Name] != null && ds.Tables[0].Rows[0][p.Name].ToString() != "")
                        {
                            object value = this.ChangeType(ds.Tables[0].Rows[0][p.Name], p.PropertyType);
                            p.SetValue(t, value, null);
                        }

                    }

                }
                else
                {
                    return default(T);
                }
            }
            return t;

        }

        ///// <summary>
        ///// 得到一个对象实体
        ///// </summary>
    public T GetEntityByWhere<T>(string whereStr) where T : new()
    {
        T t = new T();
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties();
        CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

        // return t;
        StringBuilder strSql = new StringBuilder();
        DBType dbType = OConfig.SysDBType;
        IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
        strSql.Append("select  ");
        strSql.Append(" * ");
        strSql.Append(" from ");
        strSql.Append(classAttribute.TableName);
        strSql.Append(" " + whereStr + " ");
        //strSql.Append(classAttribute.KeyName + "='" + key + "' ");

        DataSet ds = DB.ExecuteDataSet(strSql.ToString(), CommandType.Text, null);
        if (ds.Tables[0].Rows.Count > 0)
        {
            foreach (PropertyInfo p in properties)
            {
                if (ds.Tables[0].Columns.Contains(p.Name) && ds.Tables[0].Rows[0][p.Name] != null && ds.Tables[0].Rows[0][p.Name].ToString() != "")
                {
                    object value = this.ChangeType(ds.Tables[0].Rows[0][p.Name], p.PropertyType);
                    p.SetValue(t, value, null);
                }

            }

        }
        else
        {
            return default(T);
        }
        return t;

    }

        ///// <summary>
        ///// 删除记录
        ///// </summary>
    public bool DelEntity<T>(T t)
    {
        try
        {
            Type type = t.GetType();
            PropertyInfo[] properties = type.GetProperties();
            CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

            StringBuilder strSql = new StringBuilder();
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            strSql.Append("delete from " + classAttribute.TableName);
            strSql.Append(" where " + classAttribute.KeyName + "='" + type.GetProperty(classAttribute.KeyName).GetValue(t, null) + "' ");
            int isSuccess = DB.ExecuteNonQuery(strSql.ToString(), CommandType.Text, null);
            if (isSuccess > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
    }

        ///// <summary>
        ///// 删除记录通过SQL
        ///// </summary>
    public bool DelEntityBySql(string strSql)
    {
        try
        {
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            int isSuccess = DB.ExecuteNonQuery(strSql, CommandType.Text, null);
            if (isSuccess > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }
    }

    public bool ExecuteNonQuery(string sql)
    {
        DBType dbType = OConfig.SysDBType;
        IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
        int isSuccess = DB.ExecuteNonQuery(sql, CommandType.Text, null);
        if (isSuccess >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

        ///// <summary>
        ///// 添加一条记录
        ///// </summary>
    public bool AddEntity<T>(T t)
    {
        try
        {
            Type type = t.GetType();
            PropertyInfo[] properties = type.GetProperties();
            CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

            StringBuilder strSql = new StringBuilder();
            StringBuilder strSql1 = new StringBuilder();
            StringBuilder strSql2 = new StringBuilder();
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);

            foreach (PropertyInfo p in properties)
            {
                if (p.GetValue(t, null) != null)
                {

                    if (p.Name == "ID")
                    {
                        continue;
                    }
                    Type pType = p.PropertyType;
                    if (pType.IsGenericType && pType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                    {

                        NullableConverter nullableConverter = new NullableConverter(pType);
                        pType = nullableConverter.UnderlyingType;
                    }
                    string value = "";
                    if (pType.FullName == "System.DateTime")
                    {
                        value = "to_date('" + p.GetValue(t, null) + "','yyyy-mm-dd hh24:mi:ss'),";
                    }
                    else
                    {


                        value = "'" + p.GetValue(t, null) + "',";
                    }

                    strSql1.Append("["+p.Name + "],");
                    strSql2.Append(value);
                }
            }

            strSql.Append("insert into " + classAttribute.TableName + " (");
            strSql.Append(strSql1.ToString().Remove(strSql1.Length - 1));
            strSql.Append(")");
            strSql.Append(" values (");
            strSql.Append(strSql2.ToString().Remove(strSql2.Length - 1));
            strSql.Append(")");
            int isSuccess = DB.ExecuteNonQuery(strSql.ToString(), CommandType.Text, null);
            if (isSuccess > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }

    }

        ///// <summary>
        ///// 编辑一条记录
        ///// </summary>
        ///// <param name="model"></param>
        ///// <returns></returns>
    public bool EditEntity<T>(T t)
    {
        try
        {
            Type type = t.GetType();
            PropertyInfo[] properties = type.GetProperties();
            CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

            StringBuilder strSql = new StringBuilder();
            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
            strSql.Append("update " + classAttribute.TableName + " set ");

            String where = "";
            foreach (PropertyInfo p in properties)
            {
                if (p.GetValue(t, null) != null)
                {
                    //if (p.Name == "ID")
                    //{
                    //    continue;
                    //}
                    Type pType = p.PropertyType;
                    if (pType.IsGenericType && pType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
                    {

                        NullableConverter nullableConverter = new NullableConverter(pType);
                        pType = nullableConverter.UnderlyingType;
                    }
                    if (classAttribute.KeyName == p.Name)
                    {
                        if (pType.FullName == "System.DateTime")
                            where = " where " + classAttribute.KeyName + "=to_date('" + type.GetProperty(classAttribute.KeyName).GetValue(t, null) + "','yyyy-mm-dd hh24:mi:ss') ";
                        else
                        {
                            if(pType.FullName=="System.Int32")
                            {
                                where = " where " + classAttribute.KeyName + "=" + type.GetProperty(classAttribute.KeyName).GetValue(t, null) + " ";
                            }
                            else
                            where = " where " + classAttribute.KeyName + "='" + type.GetProperty(classAttribute.KeyName).GetValue(t, null) + "' ";
                        }
                        continue;
                    }
                    else
                    {
                        if (pType.FullName == "System.DateTime")
                        {
                            strSql.Append("["+p.Name + "]=to_date('" + p.GetValue(t, null) + "','yyyy-mm-dd hh24:mi:ss'),");
                        }
                        else
                        {
                            if (pType.FullName == "System.Int32")
                            {
                                strSql.Append("[" + p.Name + "]=" + p.GetValue(t, null) + ",");
                            }
                            else
                                strSql.Append("[" + p.Name + "]='" + p.GetValue(t, null) + "',");
                        }
                    }

                }
            }

            int n = strSql.ToString().LastIndexOf(",");
            strSql.Remove(n, 1);

            strSql.Append(where);

            int isSuccess = DB.ExecuteNonQuery(strSql.ToString(), CommandType.Text, null);
            if (isSuccess > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        catch (Exception e)
        {
            return false;
        }

    }

        ///// <summary>
        ///// 得到对象实体集合
        ///// </summary>
    public List<T> GetEntityList<T>(string WhereStr) where T : new()
    {
        //T o;
        // o.GetType
        List<T> entityList = new List<T>();
        Type type = typeof(T);
        PropertyInfo[] properties = type.GetProperties();
        CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

        // return t;
        StringBuilder strSql = new StringBuilder();
        DBType dbType = OConfig.SysDBType;
        IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);
        strSql.Append("SELECT  ");
        strSql.Append(" * ");
        strSql.Append(" FROM ");
        strSql.Append(classAttribute.TableName);
        if (!string.IsNullOrEmpty(WhereStr))
        {
            strSql.Append(WhereStr);
        }

        DataSet ds = DB.ExecuteDataSet(strSql.ToString(), CommandType.Text, null);
        if (ds.Tables[0].Rows.Count > 0)
        {

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                T entity = new T();
                foreach (PropertyInfo p in properties)
                {
                    if (ds.Tables[0].Columns.Contains(p.Name) && ds.Tables[0].Rows[i][p.Name] != null && ds.Tables[0].Rows[i][p.Name].ToString() != "")
                    {
                        object value = this.ChangeType(ds.Tables[0].Rows[i][p.Name], p.PropertyType);
                        p.SetValue(entity, value, null);
                    }

                }
                entityList.Add(entity);
            }
        }
        return entityList;

    }

        ////Nullable类型处理
    public object ChangeType(object value, Type conversionType)
    {
        if (value == null)
            return null;
        if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
        {
            if (value != null)
            {
                NullableConverter nullableConverter = new NullableConverter(conversionType);
                conversionType = nullableConverter.UnderlyingType;
            }
            else
            {
                return null;
            }
        }

        return Convert.ChangeType(value, conversionType);
    }

        ///// <summary>
        ///// 得到对象实体集合
        ///// </summary>
        public List<T> GetEntityListBySql<T>(string sqlstr) where T : new()
        {
            //T o;
            // o.GetType
            List<T> entityList = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            CustomAttribute classAttribute = (CustomAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(CustomAttribute));

            // return t;

            DBType dbType = OConfig.SysDBType;
            IDBAccess DB = DBFactory.GetDBAccess(dbType, OConfig.DBConnection);



            DataSet ds = DB.ExecuteDataSet(sqlstr, CommandType.Text, null);
            if (ds.Tables.Count > 0)
            {
                if (ds.Tables[0].Rows.Count > 0)
                {

                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        T entity = new T();
                        foreach (PropertyInfo p in properties)
                        {
                            if (ds.Tables[0].Columns.Contains(p.Name) && ds.Tables[0].Rows[i][p.Name] != null && ds.Tables[0].Rows[i][p.Name].ToString() != "")
                            {
                                object value = this.ChangeType(ds.Tables[0].Rows[i][p.Name], p.PropertyType);
                                p.SetValue(entity, value, null);
                            }

                        }
                        entityList.Add(entity);
                    }
                }
            }
            return entityList;

        }


    public DataTable GetDataTableBySql(string sql)
    {
        DataTable table = null;
        try
        {
            IDBAccess DB = DBFactory.GetDBAccess(OConfig.SysDBType, OConfig.DBConnection);
            table = DB.ExecuteDataTable(sql, CommandType.Text, null);
        }
        catch (Exception exp)
        {
            table = null;
        }
        finally
        {
        }
        //mc.ClosePool();
        return table;
    }

      
       

      
        
       

    }
